package com.weblog.web.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weblog.common.domain.dos.UserDO;
import com.weblog.common.domain.dos.UserRoleDO;
import com.weblog.common.domain.mapper.UserMapper;
import com.weblog.common.domain.mapper.UserRoleMapper;
import com.weblog.common.enums.ResponseCodeEnum;
import com.weblog.common.exception.DataConflictException;
import com.weblog.web.model.vo.user.RegisterParam;
import com.weblog.web.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
    @Resource
    UserMapper userMapper;

    @Resource
    UserRoleMapper userRoleMapper;

    @Override
    public void register(RegisterParam registerParam) {
        String username = registerParam.getUsername();
        String password = registerParam.getPassword();
        UserDO user = getOne(Wrappers.<UserDO>lambdaQuery().eq(UserDO::getUsername, username));
        if (!Objects.isNull(user)) {
            throw new DataConflictException(ResponseCodeEnum.DATA_CONFLICT_ERROR);
        }
        try {
            userMapper.insert(UserDO.builder()
                    .username(username)
                    .password(new BCryptPasswordEncoder().encode(password))
                    .createTime(new Date())
                    .updateTime(new Date())
                    .isDeleted(false)
                    .build());
            userRoleMapper.insert(UserRoleDO.builder()
                    .username(username)
                    .role("ROLE_VISITOR")
                    .createTime(new Date()).build());
        } catch (Exception e) {
            log.error("未知错误");
        }
    }
}
